
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { Router } from '@angular/router';
@Component({
  selector: 'business-department-add',
  templateUrl: './add.component.html',
})
export class BusinessDepartmentAddComponent implements OnInit, OnDestroy {
  form: FormGroup;
  submitting = false;
  object: any = localStorage['currentData']?JSON.parse(localStorage['currentData']): '';

  constructor(
    private fb: FormBuilder,
    private http: _HttpClient,
    private router: Router,
    private msg: NzMessageService) {}

  ngOnInit(): void {
    if(this.object) {
      this.form = this.fb.group({
        depName: [this.object.depName, [Validators.required]],
        depSup: [this.object.depSup, [Validators.required]],
        depLead: [this.object.depLead, [Validators.required]],
        depDescribe: [this.object.depDescribe],
        depStatus: [this.object.depStatus]
      });
    }else{
      this.form = this.fb.group({
        depName: ['', [Validators.required]],
        depSup: ['无', [Validators.required]],
        depLead: ['', [Validators.required]],
        depDescribe: [''],
        depStatus: ['启用']
      });
    }
  }

  submit() {
    if(this.form.valid) {
      this.submitting = true;
      let values = this.form.value;
      let obj = {
        depName: values.depName,
        depSup: values.depSup,
        depLead: values.depLead,
        depDescribe: values.depDescribe,
        depStatus: values.depStatus
      }
      if(this.object) {
        obj['_id'] = this.object._id;
        this.http.patch('api/department/update/', obj).subscribe((res: any) => {
          this.submitting = false;
          if(res.success) {
            this.msg.success(`修改成功`);
            // 路由跳转
            this.router.navigate(['/business/department/list']);
          }else{
            this.msg.error(`部门已存在`);
          }
        }, () => {
          this.msg.error(`网络请求失败`);
        });
      }else {
        this.http.post('api/department/add/', obj).subscribe((res: any) => {
          this.submitting = false;
          if(res.success) {
            this.msg.success(`添加成功`);
            // 路由跳转
            this.router.navigate(['/business/department/list']);
          }else{
            this.msg.error(`部门已存在`);
          }
        }, () => {
          this.msg.error(`网络请求失败`);
        });
      }
    }
  }
  ngOnDestroy() {
    if(this.object) {
      localStorage.removeItem('currentData');
    }
  }
}
